export class XinXiKuang extends HTMLElement {
	wenBen = null // 显示的文本
    #chuFaYuanSu = null // 触发元素

	constructor() {
		super()

		let shadow = this.attachShadow({ mode: 'open' })

		let chaCao = document.createElement('slot')
		shadow.appendChild(chaCao)
		
		this.wenBen = document.createElement('div')
        this.wenBen.style = `
            color: #fff;
			font-size: 15px;
            padding: 10px;
			border-radius: 5px;
			background-color: rgba(0, 0, 0, 0.8);
			box-shadow: 0px 0px 10px 5px rgba(63, 127, 255, 0.2);
			text-shadow: 3px 3px 2px rgba(100, 100, 200, 0.2);
        `
		shadow.appendChild(this.wenBen)
	}

	connectedCallback() {
		this.style = `
			${this.style.cssText}
			position: absolute;
            z-index: 10;
            display: block;
			max-width: 30rem;
            visibility: hidden;
		`
	}

    get chuFaYuanSu () {
        return this.#chuFaYuanSu
    }
    
    set chuFaYuanSu (chuFaYuanSu) {
        this.#chuFaYuanSu = chuFaYuanSu

        chuFaYuanSu.addEventListener('pointerenter', shiJian => {
			document.body.appendChild(this)
		})

		chuFaYuanSu.addEventListener('pointermove', shiJian => {
			this.xianShi(shiJian)
		})

		chuFaYuanSu.addEventListener('pointerleave', shiJian => {
			this.remove()
		})

		let fangFa = () => {
			if (!this.ownerDocument) this.xinXiKuang.remove()
		}
    
		document.body.addEventListener('pointermove', shiJian => {
			if (!chuFaYuanSu.isConnected) {
				this.remove()
				document.body.removeEventListener('pointermove', fangFa)
			}
		})
    }
    /**
     * 
     * @param {MouseEvent} shiJian 事件
     * @param {String} wenBen 文本
     */
    xianShi(shiJian) {
        const jianGe = 5 // 指针与框的间隔，避免指针在框上，触发元素pointerleave
		const clientWidth = document.documentElement.clientWidth
		const clientHeight = document.documentElement.clientHeight

		let { x, y } = shiJian
		let { width, height } = this.getBoundingClientRect()

		if (x + width + jianGe > clientWidth) x -= width
		if (y + height + jianGe > clientHeight) y -= height

		this.style.visibility = 'visible'
		this.style.left = `${x + jianGe}px`
		this.style.top = `${y + jianGe}px`
    }
}

customElements.define("xin-xi-kuang", XinXiKuang)


